package org.kailu.book.controller;

import org.kailu.book.entity.BookEntity;
import org.kailu.book.service.AuthorService;
import org.kailu.book.service.BookService;
import org.kailu.book.service.CategoryService;
import org.kailu.book.service.CustomerService;
import org.kailu.book.service.LanguageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author viet.ch
 * @generated May 25, 2014
 * @from Ho Chi Minh, VN
 */

@Controller
public class BookController {

	@Autowired
	private BookService bookService;
	@Autowired
	private AuthorService authorService;
	@Autowired
	private LanguageService languageService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private CustomerService customerService;
	
	@RequestMapping("book")
	private String getData(ModelMap map) {
		map.addAttribute("bookList", bookService.getAll());
		return "book";
	}
	
	@RequestMapping(value = "/book/saveorupdate", method = RequestMethod.GET)
	public String initData(ModelMap map) {
		map.addAttribute("book",new BookEntity());
		map.addAttribute("authorList", authorService.getAll());
		map.addAttribute("languageList", languageService.getAll());
		map.addAttribute("categoryList", categoryService.getAll());
		return "book_new";
	}
	
	@RequestMapping(value = "/book/saveorupdate", method = RequestMethod.POST)
    public String save(@ModelAttribute(value="book") BookEntity bookEntity, BindingResult result)
    {
		bookService.saveOrUpdate(bookEntity);
		System.out.println("ID of book: "+bookEntity.getBookId());
		return "redirect:/book";
    }
	
	@RequestMapping(value = "/book/saveorupdate/{bookId}", method = RequestMethod.GET)
    public String update(@PathVariable("bookId") int bookId, ModelMap map)
    {
		map.addAttribute("book", bookService.get(bookId));
		map.addAttribute("authorList", authorService.getAll());
		map.addAttribute("languageList", languageService.getAll());
		map.addAttribute("categoryList", categoryService.getAll());
		return "book_new";
    }
	
	@RequestMapping(value = "/book/delete/{bookId}", method = RequestMethod.GET)
    public String delete(@PathVariable("bookId") int bookId)
    {
		this.bookService.delete(bookId);
		return "redirect:/book";
    }
	
}
